package main

import (
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
	"strings"
)

func init() {

}

func main() {
	router := gin.Default()

	router.GET("/*filepath", func(context *gin.Context) {
		uri := context.Request.URL.RequestURI()
		response, _ := http.Get("http://www.baidu.com" + uri)
		//reader := response.Body
		addr := string("127.0.0.1:8089")
		reader := relpaceAll(response, &addr)
		length := response.ContentLength
		contentType := response.Header.Get("Content-Type")
		context.DataFromReader(200, length, contentType, reader, nil)

	})
	// 记录到文件。
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	router.Run(":8089")
}
func relpaceAll(response *http.Response, newAddr *string) io.Reader {
	contentType := response.Header.Get("Content-Type")
	if strings.HasPrefix(contentType, "text/") {
		builder := &strings.Builder{}
		io.Copy(builder, response.Body)
		all := strings.ReplaceAll(builder.String(), "http://www.baidu.com", *newAddr)
		all = strings.ReplaceAll(all, "https://www.baidu.com", *newAddr)
		all = strings.ReplaceAll(all, "www.baidu.com", *newAddr)
		return strings.NewReader(all)
	} else {
		return response.Body
	}
}
